<template>
  <el-col :span="24">
    <el-card class="card">
      <DateSelect class="pull-right" @getTime="getTime"></DateSelect>
      <el-button type="primary" @click="addMessage" :disabled="isSubmit" class="addBtn pull-left mb20">今日打卡</el-button>
      <el-table :data="data.slice((page-1)*pagesize,page*pagesize)" style="width: 100%" empty-text="暂无打卡记录，请及时打卡">
        <el-table-column prop="dateId" :formatter="tabFormatter" fixed label="日期" width="160"></el-table-column>
        <el-table-column prop="position" label="地点" width="160"></el-table-column>
        <el-table-column prop="state" :formatter="tabFormatter" label="目前身体健康状态" width="180"></el-table-column>
        <el-table-column label="昨日中午体温">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.temperature1 }}℃</span>
          </template>
        </el-table-column>
        <el-table-column prop="temperature2" label="昨日晚上体温">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.temperature2 }}℃</span>
          </template>
        </el-table-column>
        <el-table-column prop="temperature" label="今日早上体温">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.temperature }}℃</span>
          </template>
        </el-table-column>
        <el-table-column prop="healthCode" :formatter="tabFormatter" label="健康码" width="110"></el-table-column>
        <el-table-column fixed="right" label="操作" width="260" align="center">
          <template slot-scope="scope">
            <el-button @click="replyWin(scope.row,true)" size="mini">编辑</el-button>
            <el-button @click="replyWin(scope.row,false)" size="mini">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="健康日报表" :visible.sync="isOpen" width="45%" :before-close="beforeClose">
        <div>
          <el-form :model="dataForm" :rules="rules" ref="dataForm" label-width="120px">
            <el-form-item label="目前身体状况">
              <el-radio-group v-model="dataForm.state" :disabled="isDisabled">
                <el-radio :label="1">健康</el-radio>
                <el-radio :label="2">体温大于37.3度</el-radio>
                <el-radio :label="3">有发烧、干咳等异常情况</el-radio>
                <el-radio :label="4">其他</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="昨日中午体温" :rules="rules.temperature" prop="temperature1">
              <el-input v-model="dataForm.temperature1" :disabled="isDisabled"></el-input>
            </el-form-item>
            <el-form-item label="昨日晚上体温" :rules="rules.temperature" prop="temperature2">
              <el-input v-model="dataForm.temperature2" :disabled="isDisabled"></el-input>
            </el-form-item>
            <el-form-item label="今日早上体温" :rules="rules.temperature" prop="temperature">
              <el-input v-model="dataForm.temperature" :disabled="isDisabled"></el-input>
            </el-form-item>
            <el-form-item label="健康码">
              <el-radio-group v-model="dataForm.healthCode" :disabled="isDisabled">
                <el-radio :label="1">绿色</el-radio>
                <el-radio :label="2">黄色</el-radio>
                <el-radio :label="3">红色</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isOpen = false">取 消</el-button>
          <el-button v-if="isEdit" type="primary" @click="submitForm('dataForm')">更新</el-button>
          <el-button v-else-if="!isDisabled" type="primary" @click="submitForm('dataForm')">提交</el-button>
        </span>
      </el-dialog>
      <Paging @curr-page="currPage" :total="total"></Paging>
    </el-card>
  </el-col>
</template>

<script>
import Paging from "../components/Paging"
import DateSelect from '../components/DateSelect'
import {
  axiosUtil
} from "../network/axiosUtil"
import formatTime from '../utils/formatTime'

export default {
  name: "Mail",
  data () {
    var validateInput = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('该项不能为空'));
      }
      value = Number(value)
      if (!Number.isFinite(value) || value < 32 || value > 42) {
        callback(new Error('请输入正确的体温数值，例：36.7'));
      } else {
        callback();
      }
    };
    return {
      data: [],
      isDisabled: false,
      isOpen: false,
      isEdit: false,
      isSubmit: false,
      username: '',
      dateId: '',
      startTime: '',
      endTime: '',
      dataForm: {
        state: 1,
        dateId: '',
        username: '',
        temperature1: '',
        temperature2: '',
        temperature: '',
        healthCode: 1
      },
      position: '',
      rules: {
        temperature: [{
          validator: validateInput,
          trigger: "blur"
        }]
      },
      total: 0, //返回数据总数
      pagesize: 10,
      page: 1 //当前页数
    }
  },
  methods: {
    // 表格数据格式化
    tabFormatter (row, column, cellValue, index) {
      if (column.property == 'state') {
        switch (cellValue) {
          case 1:
            return "健康"
          case 2:
            return "体温大于37.3度"
          case 3:
            return "有发烧、干咳等异常情况"
          case 4:
            return "其他"
        }
      }
      if (column.property == 'healthCode') {
        switch (cellValue) {
          case 1:
            return "绿色"
          case 2:
            return "黄色"
          case 3:
            return "红色"
          default:
            break;
        }
      }
      if (column.property == 'dateId') {
        const format = n => {
          if (cellValue.charAt(n) == 0) {
            return cellValue.charAt(n + 1)
          } else {
            return cellValue.slice(n, n + 2)
          }
        }
        let str = cellValue.slice(0, 4) + '年' + format(4) + '月' + format(6) + '日'
        // let html = <i class="el-icon-time">{str} </i>
        return str
      }
    },
    //转换时间格式
    dateFormat (row, col) {
      let resDate
      let date = row.dateId
      if (date != null) {
        resDate = this.formatTime(date)
      }
      return resDate
    },

    formatTime (time) { //格式化时间
      return formatTime(time, "yyyyMMdd")
    },
    //打开窗口，默认显示对方用户名，且不可修改
    replyWin (row, flag) {
      console.log(this)
      this.isOpen = true
      this.isDisabled = !flag
      this.isEdit = flag
      this.dataForm = row
    },

    getTime (time) {
      this.startTime = formatTime(time[0], "yyyyMMdd")
      this.endTime = formatTime(time[1], "yyyyMMdd")
      this.queryTable()
    },

    addMessage () {
      this.isOpen = true
      this.isDisabled = false
      this.isEdit = false
    },

    submitForm (dataForm) {
      this.$refs[dataForm].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.updateMessage(dataForm)
          } else {
            this.sendMessage(dataForm)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //点击右上角的关闭按钮前，也需要询问是否放弃本次提交
    beforeClose (done) {
      if (this.isDisabled) {
        done()
      } else {
        let state = confirm("是否放弃提交？")
        if (!state) {
          this.sendMessage('dataForm')
        } else {
          done()
        }
      }
    },
    /**
     * 添加打卡信息，发送请求
     * */
    sendMessage (dataForm) {
      var params = this.$refs[dataForm].model
      params.username = this.username
      params.position = this.position
      params.dateId = this.formatTime(new Date())
      axiosUtil({
        url: '/message/add',
        method: 'POST',
        data: {
          message: params,
        }
      }).then(data => {
        if (data) {
          this.$message({
            message: '打卡成功',
            type: 'success'
          });
          this.isOpen = false
          this.isSubmit = true
          document.querySelector('.addBtn').innerHTML = '今日已打卡'
          this.queryTable()
        } else {
          this.$message.error('打卡失败');
        }
      })
    },
    /**
     * 更新打卡信息，发送请求
     * */
    updateMessage (dataForm) {
      var params = this.$refs[dataForm].model
      params.username = this.username
      axiosUtil({
        url: '/message/update',
        method: 'POST',
        data: {
          message: params,
        }
      }).then(data => {
        if (data) {
          this.$message({
            message: '更新成功',
            type: 'success'
          });
          this.isOpen = false
          this.queryTable()
        } else {
          this.$message.error('更新失败');
        }
      })
    },
    currPage (currPage) {
      this.page = currPage
    },
    queryTable () {
      axiosUtil({
        url: '/message/find',
        method: 'get',
        params: {
          username: this.username,
          startTime: this.startTime,
          endTime: this.endTime,
        }
      }).then(data => {
        if (data && data != '') {
          this.data = data
          this.total = data.length
        } else {
          this.data = []
        }
      })
    },
    checkMessage () {
      axiosUtil({
        url: '/message/find',
        method: 'get',
        params: {
          username: this.username,
          startTime: formatTime(new Date(), "yyyyMMdd"),
          endTime: formatTime(new Date(), "yyyyMMdd"),
        }
      }).then(data => {
        if (data && data.length != 0) {
          this.isSubmit = true
          document.querySelector('.addBtn').innerHTML = '今日已打卡'
        } else {
          this.isSubmit = false
          document.querySelector('.addBtn').innerHTML = '今日打卡'
        }
      })
    }
  },

  created () {
    this.username = this.$store.state.userInfo.user.username
    this.position = this.$store.state.userInfo.position.address
    this.checkMessage()
  },
  components: {
    Paging,
    DateSelect
  }
}
</script>

<style scoped>
</style>